//
//  String+Size.swift
//  TTCOM
//
//  Created by Toj on 1/18/24.
//

import Foundation

// MARK: - string 宽高
public extension String {
    
    /**
     获取不同行数高度
     
     - Parameter font: 字体大小
     */
    static func st_stringHeight(
        line count: Int,
        font: TTFont
    ) -> CGFloat {
        guard count > 0 else { return 0 }
        
        var lineString = "*"
        for _ in 1..<count {
            lineString += "\n*"
        }
        
        let height = lineString.cm_stringHeight(font: font, maxWidth: 1)
        return height
    }
    
    func cm_stringOneLineHeight(font: TTFont) -> CGFloat {
        return cm_stringHeight(font: font, maxWidth: CGFloat(MAXFLOAT))
    }
    
    func cm_stringOneLineWidth(font: TTFont) -> CGFloat {
        return cm_stringWidth(font: font, maxHeight: CGFloat(MAXFLOAT))
    }
    // 同上
    func cm_stringOneLineWidth1(font: TTFont) -> CGFloat {
        return cm_stringWidth(font: font, maxHeight: 1)
    }
    
    /** 计算宽度 +1 为了容错 */
    func cm_stringWidth(font: TTFont, maxHeight: CGFloat) -> CGFloat {
        let maxSize = CGSize(width: CGFloat(MAXFLOAT), height: maxHeight)
        return cm_stringSize(font: font, maxSize: maxSize).width + 1
    }
    
    func cm_stringHeight(font: TTFont, maxWidth: CGFloat) -> CGFloat {
        let maxSize = CGSize(width: maxWidth, height: CGFloat(MAXFLOAT))
        return cm_stringSize(font: font, maxSize: maxSize).height
    }
    
    func cm_stringSize(fontSize: CGFloat, maxSize: CGSize) -> CGSize {
        let font = TTFont.systemFont(ofSize: fontSize)
        return cm_stringSize(font: font, maxSize: maxSize)
    }
    
    func cm_stringSize(font: TTFont, maxSize: CGSize) -> CGSize {
        let attributes = [NSAttributedString.Key.font:font]
        
#if canImport(UIKit)
        let option: NSStringDrawingOptions = .usesLineFragmentOrigin
#endif
        
#if canImport(AppKit)
        let option = NSString.DrawingOptions.usesLineFragmentOrigin
#endif
        
        let rect = self.boundingRect(with: maxSize, options: option, attributes: attributes, context: nil)
        return CGSize(width: rect.width + 1, height: rect.height + 1)
    }
}
